package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import com.etoak.common.core.exception.CustomException;
import com.etoak.common.core.vo.PageVo;
import com.etoak.entity.Dishes;
import com.etoak.mapper.DishesMapper;
import com.etoak.service.DishesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.vo.DishesVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author etoak
 * @since 2025-08-25
 */
@Service
public class DishesServiceImpl extends ServiceImpl<DishesMapper, Dishes> implements DishesService {

    @Override
    public void add(Dishes dishes) {
        if(ObjectUtils.isNotEmpty(getByName(dishes.getName()))) {
            throw new CustomException("菜品名称重复");
        }
        dishes.setCreateTime(DateUtil.now());
        this.save(dishes);
    }

    @Override
    public PageVo<DishesVo> getList(int pageNum, int pageSize, Dishes dishes) {
        PageHelper.startPage(pageNum, pageSize);
        List<DishesVo> dishesVoList = baseMapper.getList(dishes);
        PageInfo<DishesVo> pageInfo = new PageInfo<>(dishesVoList);
        return new PageVo<>(pageInfo.getTotal(), dishesVoList);
    }

    @Override
    public void updateDishes(int id, Dishes dishes) {
        //判断是否存在该菜品(通过id查询菜品)
        if(ObjectUtils.isEmpty(this.getById(id))){
            throw new CustomException("菜品不存在！");
        }
        String dishesName = dishes.getName();
        //如果传入的名字不为空通过名称查询该菜品
        if(StringUtils.isNoneBlank(dishesName)) {
            //通过该名称查询数据库中的菜
            Dishes saveDishes=this.getByName(dishesName);
            //如果查询出来不为空，并且id不一样就为重复（新修改的名称和数据库中的名称不能一样）
            if(ObjectUtils.isNotEmpty(saveDishes) && !saveDishes.getId().equals(id)) {
                throw new CustomException("不孬将名称修改为其他菜品名称");
            }
        }
        dishes.setId(id);
        dishes.setUpdateTime(DateUtil.now());
        this.updateById(dishes);
    }

    @Override
    public void delete(int id) {
        if(ObjectUtils.isEmpty(this.getById(id))){
            throw new CustomException("菜品不存在");
        }
        this.removeById(id);
    }

    private Dishes getByName(String dishName) {
        return lambdaQuery().eq(Dishes::getName, dishName).one();
    }
}
